package first;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import javax.imageio.stream.FileImageInputStream;

import com.lowagie.text.Document;
import com.lowagie.text.Image;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfCopy;
import com.lowagie.text.pdf.PdfImportedPage;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfWriter;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;

public class PDFtoIMAGE {
	public static void main(String[] args) throws Exception {

		// PDFtoIMAGE.imgMerageToPdf(new File("D:/111").listFiles(),new File("D:/","yyy.pdf"));
		//PDFtoIMAGE.pdfToJpg("D:/sb.pdf", "D:/222", 1, 0);
		//PDFtoIMAGE.pdfTopdf("D:/sb.pdf", "D:/111/1.pdf", 1);
		PDFtoIMAGE.jpgToPdf(new File("c:/test/tes.jpg"),new File("c:/test/a.pdf"));
	}

	private static void listOrder(String target) {
		File[] listFiles = new File(target).listFiles();
		TreeMap<Integer, File> tree = new TreeMap<Integer, File>();
		for (int i=0;i<listFiles.length;i++) {
			File f=listFiles[i];
			tree.put((i+1), f);
		}
		for (Entry<Integer, File> eif : tree.entrySet()) {
			System.out.println(eif.getKey() + "=" + eif.getValue().toString());
		}
	}

	public static boolean imgMerageToPdf(File[] list, File file)
			throws Exception {
		Map<Integer, File> mif = new TreeMap<Integer, File>();
		for (int i = 0; i < list.length; i++) {
			File f = list[i];
			mif.put((i + 1), f);
		}

		ByteArrayOutputStream baos = new ByteArrayOutputStream(2048 * 3);
		InputStream is = new FileInputStream(mif.get(1));
		for (int len; (len = is.read()) != -1;)
			baos.write(len);

		baos.flush();
		Image image = Image.getInstance(baos.toByteArray());
		float width = image.getWidth();
		float height = image.getHeight();
		baos.close();

		Document document = new Document(new Rectangle(width, height));
		PdfWriter pdfWr = PdfWriter.getInstance(document, new FileOutputStream(
				file));
		document.open();

		for (Entry<Integer, File> eif : mif.entrySet()) {
			baos = new ByteArrayOutputStream(2048 * 3);
			is = new FileInputStream(eif.getValue());
			for (int len; (len = is.read()) != -1;)
				baos.write(len);
			baos.flush();

			image = Image.getInstance(baos.toByteArray());
			Image.getInstance(baos.toByteArray());
			image.setAbsolutePosition(0.0f, 0.0f);
			
			document.add(image);
			document.newPage();
			baos.close();
		}

		document.close();
		pdfWr.close();

		return true;
	}

	private static boolean pdfToJpg(String source, String target, int start,
			int end) throws Exception {
		if (start > end&&end!=0) {
			System.out.println("start do not big end");
			return false;
		}
		
		RandomAccessFile rea = new RandomAccessFile(new File(source), "r");
		
		FileChannel channel = rea.getChannel();
		ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0,
				channel.size());
		
		PDFFile pdfFile = new PDFFile(buf);
		if (end == 0) {
			end = pdfFile.getNumPages();
		}
		for (int i = start; i <= end; i++) {
			PDFPage	page = pdfFile.getPage(i);
			// get the width and height for the doc at the default zoom
			java.awt.Rectangle rect = new java.awt.Rectangle(0, 0, (int) page
					.getBBox().getWidth(), (int) page.getBBox().getHeight());
			// generate the image
			java.awt.Image img = page.getImage(rect.width, rect.height, // width
																		// &
					rect, // clip rect
					null, // null for the ImageObserver
					true, // fill background with white
					true // block until drawing is done
					);

			BufferedImage tag = new BufferedImage(rect.width, rect.height,
					BufferedImage.TYPE_INT_RGB);

			tag.getGraphics().drawImage(img, 0, 0, rect.width, rect.height,
					null);
			FileOutputStream out = new FileOutputStream(target + "/" + i
					+ ".jpg"); 
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
			encoder.encode(tag); 
			out.close();
		}
		return true;
	}

	private static void pdfTopdf(String source, String target, int pageNum)
			throws Exception {
		PdfReader pr = new PdfReader(source);
		System.out.println("this document " + pr.getNumberOfPages() + " page");

		Document doc = new Document(pr.getPageSize(pageNum));

		PdfCopy copy = new PdfCopy(doc, new FileOutputStream(new File(target)));
		doc.open();
		doc.newPage();

		PdfImportedPage page = copy.getImportedPage(pr, pageNum);
		copy.addPage(page);

		copy.close();
		doc.close();
		pr.close();
	}

	private static void jpgToPdf(File jpgFile, File pdfFile) throws Exception {
		
		InputStream is = new FileInputStream(jpgFile);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		for (int i; (i = is.read()) != -1;) {
			baos.write(i);
		}
		baos.flush();
		
		Image img = Image.getInstance(baos.toByteArray());
		float width = img.getWidth();
		float height = img.getHeight();
		img.setAbsolutePosition(0.0F, 0.0F);
		System.out.println("width = " + width + "\theight" + height);

		Document doc = new Document(new Rectangle(width, height));
		PdfWriter pw = PdfWriter
				.getInstance(doc, new FileOutputStream(pdfFile));
		doc.open();
		doc.add(img);

		System.out.println(doc.newPage());
		pw.flush();
		baos.close();
		doc.close();
		pw.close();
	}

}
